package com.sun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.Result;
import com.sun.dto.LogDto;
import com.sun.entity.Log;
import com.sun.service.LogService;
import com.sun.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/4/8 15:53
 * @FileName: LogController
 * @Description: ""
 */
@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    private LogService logService;


    /**
     * 查询分页根据条件所有的登录日志
     */
    @RequiresAuthentication
    @GetMapping("/page")
    public Result<Page> page(int pageNum, int pageSize, String userName, String result,
                             String account, String tel, String type,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        Page<Log> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Log> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(userName), Log::getUserName, userName);
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(result), Log::getResult, result);
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(account), Log::getAccount, account);
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(tel), Log::getTel, tel);
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(type), Log::getType, type);
        lambdaQueryWrapper.gt(startTime != null, Log::getDateTime, startTime);
        lambdaQueryWrapper.lt(endTime != null, Log::getDateTime, endTime);
        logService.page(pageInfo, lambdaQueryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 导出登入日志为Excel
     *
     * @param response
     * @throws IOException
     */
    @RequiresAuthentication
    @PostMapping("/download")
    public void download(@RequestBody LogDto logDto, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<Log> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(logDto.getUserName()), Log::getUserName, logDto.getUserName());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(logDto.getResult()), Log::getResult, logDto.getResult());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(logDto.getAccount()), Log::getAccount, logDto.getAccount());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(logDto.getTel()), Log::getTel, logDto.getTel());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(logDto.getType()), Log::getType, logDto.getType());

        List<Log> list = logService.list(lambdaQueryWrapper);

        List<Log> logList = list.stream().map((item) -> {
            if ("0".equals(item.getResult())) {
                item.setResult("成功");
            } else if ("1".equals(item.getResult())) {
                item.setResult("失败");
            }
            return item;
        }).collect(Collectors.toList());

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("用户登入日志表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), Log.class).autoCloseStream(Boolean.FALSE).sheet("登入日志")
                    .doWrite(logList);
        } catch (Exception e) {
            System.out.println("1111111111");
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JsonUtils.getBeanToJson(map));
        }
    }

    /**
     * 根据id批量删除日志
     */
    @DeleteMapping("/{ids}")
    public Result<String> delete(@PathVariable Long ids) {
        logService.removeById(ids);
        return Result.success("删除成功");
    }
}
